﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;
using System.IO;

namespace workshop3
{
    public partial class Formfinalmark : Form
    {
        private Button btnAdd;
        //private System.ComponentModel.Container components = null;
        private Button txtAdd;
        //给产生的按钮定义一个数量计算器
        private int counter;
        //给产生的按钮定义相对位置的纵坐标
        private int locY;
        //给产生的文本框定义一个数量计算器
        private int counter01;
        //给产生的文本框定义相对位置的纵坐标
        private int locY1;
        int y = 315;
        int totalpercentage = 0;
        DataTable rubric = new DataTable();
        DataColumn itemid = new DataColumn("itemid");
        DataColumn itemname = new DataColumn("itemname");
        DataColumn itempercentage = new DataColumn("itempercentage");

        string rubricid;
        string courseid;
        string taskidwtf;
        string groupidwtf;
        int persentagewtf;
        int tasknum;
        int groupnum;
        int[] arr1 = new int[30];
        int[] arr2 = new int[30];
        int[] arr3 = new int[30];

        double[] final = new double[30];

        Boolean addBelong;

        List<string> yearlist = new List<string>();
        List<string> semelist = new List<string>();

        DataTable courselist = new DataTable();
        DataColumn id = new DataColumn("courseid");
        DataColumn coursename = new DataColumn("coursename");

        DataTable task = new DataTable();
        DataColumn taskid = new DataColumn("taskid");
        DataColumn name = new DataColumn("name");
        DataColumn belongto = new DataColumn("BelongTo");

        DataTable ams = new DataTable();
        DataColumn amsid = new DataColumn("id");
        DataColumn amsname = new DataColumn("name");
        DataColumn amspercentage = new DataColumn("percentage");

        public Formfinalmark()
        {
            InitializeComponent();
            //locY = this.btnAdd.Location.Y;
            //locY1 = this.txtAdd.Location.Y;
        }

        private void Formfinalmark_Load(object sender, EventArgs e)
        {
            addBelong = false;
            tasknum = 0;
            groupnum = 0;

            for (int i = 0; i < 30; i++)
                arr1[i] = -1;

            rubric.Columns.Add(itemid);
            rubric.Columns.Add(itemname);
            rubric.Columns.Add(itempercentage);

            task.Columns.Add(taskid);
            task.Columns.Add(name);

            ams.Columns.Add(amsid);
            ams.Columns.Add(amsname);
            ams.Columns.Add(amspercentage);
            //MessageBox.Show("enter");
            if (File.Exists("rubric.xml") && File.Exists("course.xml"))
            {//add data into the year and semester dataset

                //XmlDocument rubdoc = new XmlDocument();
                XmlDocument coursedoc = new XmlDocument();
                coursedoc.Load("course.xml");
                //rubdoc.Load("rubric.xml");
                string coursepath = "//course";
                //string rubpath = "//rubrics/rubric";
                XmlNodeList coursenodelist = coursedoc.SelectNodes(coursepath);
                //XmlNodeList rubnodelist = rubdoc.SelectNodes(rubpath);
                //courselist.Columns.Add(id);
                //courselist.Columns.Add(coursename);
                if (coursenodelist != null)
                {
                    for (int i = 0; i < coursenodelist.Count; i++)
                    {
                        if (yearlist.Count == 0 && semelist.Count == 0)
                        {
                            //courselist.Rows.Add(coursenodelist[i].Attributes[0].Value.ToString(),coursenodelist[i].ChildNodes[0].InnerText);
                            yearlist.Add(coursenodelist[i].ChildNodes[1].InnerText);
                            semelist.Add(coursenodelist[i].ChildNodes[2].InnerText);
                        }
                        else
                        {
                            if (yearlist.Contains(coursenodelist[i].ChildNodes[1].InnerText))
                            {
                                //continue;
                            }
                            else
                            {
                                yearlist.Add(coursenodelist[i].ChildNodes[1].InnerText);
                            }
                            if (semelist.Contains(coursenodelist[i].ChildNodes[2].InnerText))
                            {
                                //continue;
                            }
                            else
                            {
                                semelist.Add(coursenodelist[i].ChildNodes[2].InnerText);
                            }

                            //courselist.Rows.Add(coursenodelist[i].Attributes[0].Value.ToString(),coursenodelist[i].ChildNodes[0].InnerText);

                        }
                    }
                    cbyear.SelectedValueChanged -= cbyear_SelectedValueChanged;
                    cbsemester.SelectedValueChanged -= cbsemester_SelectedValueChanged;
                    cbcourse.SelectedValueChanged -= cbcourse_SelectedValueChanged;
                    //cbrubric.SelectedValueChanged -= cbrubric_SelectedValueChanged;

                    cbyear.DataSource = yearlist;
                    cbsemester.DataSource = semelist;
                    //cbcourse.DataSource = courselist;
                    //cbcourse.DisplayMember = courselist.Columns[1].ToString() ;
                    //cbcourse.ValueMember = courselist.Columns[0].ToString();

                    cbyear.SelectedValueChanged += cbyear_SelectedValueChanged;
                    cbsemester.SelectedValueChanged += cbsemester_SelectedValueChanged;
                    //cbcourse.SelectedValueChanged -= cbcourse_SelectedValueChanged;
                }
                else
                {
                    MessageBox.Show("file empty!");
                }
            }
            else
            {
                MessageBox.Show("file not exist!");
            }

        }

        private void ChangeCourse(string year, string semester)
        {//change the dataset of course drop-down box
            bool find = false;
            DataTable dt0 = new DataTable();
            DataColumn dc3 = new DataColumn("coursename");
            DataColumn dc4 = new DataColumn("courseid");
            dt0.Columns.Add(dc4);
            dt0.Columns.Add(dc3);
            if (File.Exists("course.xml"))
            {
                XmlDocument doc = new XmlDocument();
                doc.Load("course.xml");
                string path = "//course";
                XmlNodeList nodelist = doc.SelectNodes(path);
                if (nodelist.Count != 0)
                {
                    for (int i = 0; i < nodelist.Count; i++)
                    {
                        if (nodelist[i].ChildNodes[1].InnerText == year && nodelist[i].ChildNodes[2].InnerText == semester)
                        {
                            find = true;
                            dt0.Rows.Add(nodelist[i].Attributes[0].Value, nodelist[i].ChildNodes[0].InnerText);
                        }

                    }
                    if (find)
                    {
                        cbcourse.DataSource = dt0;
                        cbcourse.DisplayMember = dt0.Columns[1].ToString();
                        cbcourse.ValueMember = dt0.Columns[0].ToString();
                        cbcourse.SelectedValueChanged += cbcourse_SelectedValueChanged;
                    }


                }
                else
                {
                    MessageBox.Show("Can not find any course!");
                }

                //return dt0;

            }
            //return null;
        }

        private void cbtask_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void cbgroup_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void cbcourse_SelectedValueChanged(object sender, EventArgs e)
        {// if course value changed, load corresponding data for datagridview
            task.Clear();
            ams.Clear();
            dgvtask.DataSource = null;

            if (cbcourse.DataSource != null)
            {
                ShowTask();
                ShowAMS();
            }

        }

        private void cbyear_SelectedValueChanged(object sender, EventArgs e)
        {
            //cbrubric.DataSource = null;
            //dgvrubric.DataSource = null;

            //lblname.Text = string.Empty;
            cbcourse.DataSource = null;
            ChangeCourse(cbyear.SelectedValue.ToString(), cbsemester.SelectedValue.ToString());
        }

        private void cbsemester_SelectedValueChanged(object sender, EventArgs e)
        {
            //cbrubric.DataSource = null;
            //dgvrubric.DataSource = null;

            //lblname.Text = string.Empty;
            cbcourse.DataSource = null;
            ChangeCourse(cbyear.SelectedValue.ToString(), cbsemester.SelectedValue.ToString());
        }



        private void cbgroup_SelectedIValueChanged(object sender, EventArgs e)
        {//get the ams group form the drop-down box
            Control parent = this.Parent;
            Label selected = new Label();
            selected.Name = "lblselected";
            selected.Location = new Point(771, y);
            selected.Font = new Font("Arial", 13);
            ComboBox cb = (ComboBox)sender;
            selected.Text = cb.SelectedValue.ToString();

        }

        private void ShowTask()
        {//this function is to show all the task in the datagridview after user select one course
            XmlNodeList tasklist = ClassCreateXML.loadxmldata(cbcourse.SelectedValue.ToString(), "//course", "course.xml", "task");
            if (tasklist != null)
            {
                for (int i = 4; i <tasklist.Count-1; i++)
                {
                    task.Rows.Add(tasklist[i].Attributes[0].Value, tasklist[i].InnerText);
                    tasknum++;
                }
                dgvtask.DataSource = task;
            }
        }

        private void ShowAMS()
        {//give dataset to cbgroup drop-down box
            XmlNodeList amslist = ClassCreateXML.loadxmldata(cbcourse.SelectedValue.ToString(), "//course", "course.xml", "AMS");

            if (amslist != null)
            {
                for (int i = 0; i < amslist.Count; i++)
                {
                    ams.Rows.Add(amslist[i].Attributes[0].Value, amslist[i].Attributes[1].Value, amslist[i].InnerText);
                    int.TryParse(amslist[i].InnerText, out arr3[i]);
                    groupnum++;
                }

                cbgroup.DataSource = ams;
                cbgroup.DisplayMember = ams.Columns[1].ToString();
                cbgroup.ValueMember = ams.Columns[0].ToString();
            }
        }

        private void dgvtask_CellClick(object sender, DataGridViewCellEventArgs e)
        {// get the info of user click in datagridview
            txttask.Text = dgvtask.CurrentRow.Cells[1].Value.ToString();
            taskidwtf = dgvtask.CurrentRow.Cells[0].Value.ToString();
            cbcourse.Enabled = false;
            cbyear.Enabled = false;
            cbsemester.Enabled = false;
        }

        private void cbgroup_SelectedValueChanged(object sender, EventArgs e)
        {//get the ams group that user selected
            int total;
            int check;
            if (ams.Rows.Count > 0)
            {
                int.TryParse(cbgroup.SelectedValue.ToString(), out total);

                totalpercentage = total;
                int.TryParse(cbgroup.SelectedValue.ToString(), out check);
                lblshow.Text = arr3[check].ToString();
                groupidwtf = cbgroup.SelectedValue.ToString();
            }
        }

        private void btnok_Click(object sender, EventArgs e)
        {//if user click OK button, it will record the corresponding relation between task and ams
            // and show in the datagridview
            if (!ClassCreateXML.TextCheck(txttask.Text))
            {
                return;
            }
            if (ClassCreateXML.TextCheck(txtpercentage.Text))
            {
                return;
            }
            groupidwtf = cbgroup.SelectedValue.ToString();

            int n;
            int m;
            if (addBelong == false)
                task.Columns.Add(belongto);
            dgvtask.DataSource = task;
            int.TryParse(txtpercentage.Text.ToString(), out persentagewtf);

            if (taskidwtf != null && groupidwtf != null && persentagewtf != 0)
            {
                int.TryParse(taskidwtf, out n);
                int.TryParse(groupidwtf, out m);
                arr1[n] = m;
                arr2[n] = persentagewtf;
                //if(n<dgvtask.Rows.Count)
                dgvtask.Rows[n].Cells[2].Value = groupidwtf;
                //DataRow add = task.Select("taskid = "+taskidwtf+"")
            }

            addBelong = true;
            txttask.Clear();
            txtpercentage.Clear();

        }


        public static XmlAttribute CreateAttribute(XmlNode node, string attributeName, string value)
        {
            try
            {
                XmlDocument doc = node.OwnerDocument;       //createa new xmldocument class which is our own document   
                XmlAttribute attr = doc.CreateAttribute(attributeName);
                attr.Value = value;     //input the value in it
                node.Attributes.SetNamedItem(attr);
                return attr;
            }
            catch (Exception err)
            {
                string desc = err.Message;
                return null;
            }
        }

        private void btn_compute_Click(object sender, EventArgs e)
        {//if user click compute, it will conpute the final mark for every student in chosen course
            courseid = cbcourse.SelectedValue.ToString();
            // MessageBox.Show(courseid);
            Boolean check2 = false;
            Boolean check3 = false;
            int psum = 0;
            string studentcheck;
            for (int i = 0; i < tasknum; i++)//check whether all the tasks in the course have been set correspon ams
            {
                if (arr1[i] == -1)
                    break;
                if (i == (tasknum - 1))
                    check2 = true;
            }
            if (check2 == false)
                MessageBox.Show("please assign all tasks");
            if (check2)//check the total persentage for every task in one ams is equaul to 100 or not
            {
                MessageBox.Show("checkc2 true");
                for (int i = 0; i < groupnum; i++)
                {
                    for (int k = 0; k < tasknum; k++)
                    {
                        if (arr1[k] == i)
                        {
                            psum = psum + arr2[k];

                        }

                    }
                    if (psum != 100)
                    {
                        break;
                    }
                    if (i == (groupnum - 1))
                        check3 = true;

                    psum = 0;

                }

                if (check3 == false)
                    MessageBox.Show("the persentage is wrong");
                if (check3)//if all operation is right
                {
                    MessageBox.Show("check3 true");
                    if (File.Exists("grade.xml"))
                    {
                        XmlDocument xmldoc = new XmlDocument();
                        xmldoc.Load("grade.xml");
                        string path = "//Grades/grade[@courseid ='" + courseid + "']";
                        XmlNode node1 = xmldoc.SelectSingleNode(path);
                        XmlNode finalmark = xmldoc.CreateElement("finalgrade");
                        node1.AppendChild(finalmark);

                        for (int i = 0; i < node1.ChildNodes[0].ChildNodes.Count; i++)//operate all the student in this course
                        {
                            studentcheck = node1.ChildNodes[0].ChildNodes[i].Attributes[0].InnerText;
                            for (int n = 0; n < (node1.ChildNodes.Count - 1); n++)// operate the grade in all the task in this course
                            {
                                for (int m = 0; m < node1.ChildNodes[0].ChildNodes.Count; m++)//get current student grade in each task
                                {
                                    if (node1.ChildNodes[n].ChildNodes[m].Attributes[0].InnerText == studentcheck)
                                    {
                                        double.TryParse(node1.ChildNodes[n].ChildNodes[m].InnerText, out final[n]);
                                        final[n] = final[n] * arr2[n] / 100 * arr3[arr1[n]] / 100;
                                    }

                                }

                            }
                            for (int q = 0; q < (node1.ChildNodes.Count - 1); q++)//add together
                            {
                                final[node1.ChildNodes.Count] = final[node1.ChildNodes.Count] + final[q];

                            }

                            XmlNode student = xmldoc.CreateElement("student");
                            student.Attributes.Append(CreateAttribute(student, "studentid", studentcheck));
                            student.InnerText = final[node1.ChildNodes.Count].ToString();
                            finalmark.AppendChild(student);

                            for (int p = 0; p < 30; p++)
                            {
                                final[p] = 0;
                            }


                        }




                        xmldoc.Save("grade.xml");
                    }



                }




            }





        }

        private void btn_user_Click(object sender, EventArgs e)
        {//go back to management page
            Formmanagement user = new Formmanagement();
            user.Show();
            this.Hide();
        }
    }


}
